/*
 * @Author: GuitarXiaohe && 2205227953@qq.com
 * @Date: 2024-01-17 21:22:34
 * @LastEditors: 18163104359 2205227953@qq.com
 * @LastEditTime: 2024-01-23 18:08:18
 * @FilePath: /umi/src/models/user.ts
 * @Description:
 * QQ:2205227953,邮箱:2205227953@qq.com
 * Copyright (c) 2024 by GuitarXiaohe, All Rights Reserved.
 */
import { GetUserInfoAPI, LogoutAPI } from "@/api/common.ts";
import { removeToken, getToken } from "@/utils/auth";
import { connect, useDispatch, history } from "umi";
const user = {
  namespace: "user",
  state: {
    // 用户信息
    userInfo: {},
    // 角色信息
    roles: {},
    // 权限码
    permissions: "",
  },
  effects: {
    // 获取用户信息 改变状态值 《userInfo》
    *getUserInfo({ payload }, { call, put, select }) {
      if (!getToken()) return;
      const { permissions, roles, user } = yield call(() => GetUserInfoAPI());
      yield put({
        // 请求完事之后的调用的reducers方法
        type: "setUser",
        payload: {
          userInfo: user,
          permissions: permissions,
          roles: roles,
        },
      });
    },
    // 退出登录
    *logout({ payload }, { call, put, select }) {
      yield call(() => LogoutAPI());
      removeToken();
      history.push("/login");
    },
  },
  reducers: {
    setUser(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    update(state, { payload }) {
      console.log(state, payload);

      return {
        ...state,
        ...payload,
      };
    },
  },
};

export default user;
